// pages/test/test.js
import { ShopModel } from "../../../models/ShopModel.js"
import { AddressModel } from '../../../models/AddressModel.js'
let Address = new AddressModel()
// 引入腾讯地图SDK核心类
var QQMapWX = require('../../../utils/qqmap-wx-jssdk.js');
const key = 'Y2LBZ-LQ26W-NALRX-OKNQS-HYALF-S4F4G'; //使用在腾讯位置服务申请的key
const referer = '摇滚炒鸡-顾客端'; //调用插件的app的名称
var qqmapsdk = new QQMapWX({
    key: key // //使用在腾讯位置服务申请的key
});
let App = getApp()
// 使用腾讯地图插件
const chooseLocation = requirePlugin('chooseLocation');
Page({

    /**
     * 页面的初始数据
     */
    data: {
        location: {
            latitude: 39.984060,
            longitude: 116.307520
          },
          region: ['广东省', '广州市', '海珠区'],//所在地区
          customItem: '全部',
          detailAddress:'',//详细地址
          radio:'man',//性别默认选中 男
          invalid:'',//校验文字是否合法
          openId:'',

    },
      /**
     * 生命周期函数--监听页面加载
     */
    _init:function(){
      let that = this
      wx.getLocation({
        altitude: 'true',
        type:'gcj02',
        isHighAccuracy:'true',
        success:res=>{
            let location = {}
            location.latitude = res.latitude
            location.longitude = res.longitude

            qqmapsdk.reverseGeocoder({
              location:location,
              success:res=>{
                  let address = res.result.formatted_addresses.recommend
                  let detail = res.result.address_component
                  let region = []
                  region.push(detail.province)
                  region.push(detail.city)
                  region.push(detail.district)
                  that.setData({
                    region:region
                  })
                  that.setData({
                      detailAddress:address
                  })
                  console.log('success',res)
              }
          })
        }
      })
  },
  _getLocationAuth:function(){
    // 可以通过 wx.getSetting 先查询一下用户是否授权了 "scope.record" 这个 scope
    wx.getSetting({
      success(res) {
        console.log('res',res)
        if(!res.authSetting['scope.userLocation']) {
          that.showSettingToast("请授权")
        }
      }
    })
  },
  _getOpenId:function(){
    let openId = App.globalData.openId
    this.setData({openId})
    return openId
  },
  // 打开权限设置页提示框
  showSettingToast: function(e) {
    wx.showModal({
      title: '还未授权地理权限！',
      confirmText: '去设置',
      showCancel: false,
      content: e,
      success: function(res) {
        if (res.confirm) {
          wx.navigateTo({
            url: '/pages/setting/setting',
          })
        }
      }
    })
  },
    onLoad: function () {
      // 2、调用云函数获取openId
     this._init()
     this._getOpenId()
     this._getLocationAuth()
   },
    onShow () {
      const location = chooseLocation.getLocation(); // 如果点击确认选点按钮，则返回选点结果对象，否则返回null
      console.log('location',location)
      if(location){
        this.setData({
          detailAddress:location.name
        })
      }
    },
    onUnload () {
      // 页面卸载时设置插件选点数据为null，防止再次进入页面，geLocation返回的是上次选点结果
      chooseLocation.setLocation(null);
  },
   // 性别单选框 选择
   changeRadio(event) {
    this.setData({
      radio: event.detail,
    });
  },
  // 选择所在地区
  bindRegionChange: function (e) {
    this.setData({
      region: e.detail.value
    })
  },
 
  // 腾讯地图插件 选点
  choiceDetail:function(e){
    wx.navigateTo({
      url: 'plugin://chooseLocation/index?key=' + key + '&referer=' + referer,
    });
  
  },
    // 校验为空
    _isEmpty:function(str){
        if(str == null || str == ''){
          return true
        }else{
          return false
        }
    },
      // 校验手机号
    _isPhoneAvailable:function(poneInput) {
        var myreg=/^[1][3,4,5,7,8][0-9]{9}$/;
        if (!myreg.test(poneInput)) {
            return false;
        } else {
            return true;
        }
    },
    // 校验文字
    _checkMsg:function(msg){ 
      wx.cloud.callFunction({
       name:'ContentCheck',
       data: {
         $url:'MsgCheck',
         msg:msg
       }
     }).then(MsgRes=>{
       if (MsgRes.result.data.errCode == "87014") {
           this.setData({
               invalid:'输入含有非法内容'
           })
       }else{
           this.setData({
            invalid:''
           })
       }
     })
   },
   //提交前校验
    _submitCheck:function(customer){
      this._checkMsg(customer.name)
      let invalid = this.data.invalid
      if(!customer){
        return '请刷新后重试!'
      }
      // 1、校验收货人
      if(this._isEmpty(customer.name)){
        return  '请填写收货人!'
      }
      if(invalid !== ''){
        return '收货人输入文字不合法!'
      }
      // 2、校验联系电话
      if(this._isEmpty(customer.telephone)){
        return '请填写手机号!'
        
      }
      if(!this._isPhoneAvailable(customer.telephone)){
        return  '手机号格式错误!'
      }
      if(this._isEmpty(customer.region)){
        return '请选择所在地区!'
      }
      if(this._isEmpty(customer.detail)){
        return  '请填写详细地址!'
      }
      if(this._isEmpty(customer.sex)){
        return '请选择性别!'
      }
      // 检验合格 返回空字符串
      return ''
   },
    //  提交信息
   submit: async function(e){
    let address = e.detail.value
    let openId = this._getOpenId()
    address.openId = openId
    address.region = address.region.split(' ')
    // 将添加的地址设置为默认地址
    address.default = false
    delete address.man
    delete address.woman
    console.log('submit',address)
    let message = this._submitCheck(address)
    // 1、填入信息不完整
    if( message !== ''){
      wx.showModal({
        title: '提示',
        content:message,
        success:res=>{
          if(res.confirm){
            console.log('confirm')
          }else{
            console.log('cancel')
          }
        }
      })
     // 2、填入信息 完整
    }else{
      // 先重置地址，再添加
      await Address.createAddress(address)
      wx.navigateBack({
        delta: 1,
      })
    }
  },
   

})

